/**
 * 
 */
package com.vit.mep.manager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import net.rim.device.api.crypto.MD5Digest;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import net.rim.device.api.crypto.AESEncryptorEngine;
import net.rim.device.api.crypto.AESKey;
import net.rim.device.api.crypto.BlockEncryptor;
import net.rim.device.api.crypto.CryptoException;
import net.rim.device.api.crypto.PKCS5FormatterEngine;
import net.rim.device.api.crypto.SHA1Digest;

/**
 * @author crodriguez
 * 
 */
public class ManagerUtils {

	public String inXmlTag(String tag, String value) {
		String iniTag = "<" + tag + ">";
		String endTag = "<" + tag + "/>";
		String tmp = "";
		tmp = iniTag + value + endTag;
		return tmp;
	}

	public String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}

	public String generateEncrypted(String encrypted) {
		byte[] bytes = encrypted.getBytes();

		MD5Digest digest = new MD5Digest();
		digest.update(bytes, 0, bytes.length);
		int length = digest.getDigestLength();
		byte[] md5 = new byte[length];
		digest.getDigest(md5, 0, true);
		return convertToHex(md5);
	}

	public String encrypt(byte[] data) throws CryptoException,
			IOException {

		
		byte[] keyData = "0123456789ABCDEF".getBytes("UTF8");//change the key before the test
		
		AESKey key = new AESKey(keyData);

		AESEncryptorEngine engine = new AESEncryptorEngine(key);

		PKCS5FormatterEngine fengine = new PKCS5FormatterEngine(engine);

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		BlockEncryptor encryptor = new BlockEncryptor(fengine, output);

		SHA1Digest digest = new SHA1Digest();
		digest.update(data);
		byte[] hash = digest.getDigest();

		//String algo = engine.getAlgorithm();
		
		encryptor.write(data);
		//encryptor.write(hash);
		encryptor.close();
		output.close();

		return convertToHex(output.toByteArray());
	}

	public String getUniqueNodeValue(String nodeName, Document doc) {

		String result = "";
		NodeList nl = doc.getElementsByTagName(nodeName);
		Node node = nl.item(0);
		if (node != null) {
			result = node.getChildNodes().item(0).getNodeValue();
		}
		if (result != null)
			result = result.trim();

		return result;
	}

}// class